<template>
  <div class="online-map-location">
    <el-row :justify="align">
      <div ref="mapContainer" class="map-container" :style="getContainerStyle"></div>
    </el-row>
    <div v-if="locationInfo.address" class="location-info">
      <div class="location-address">{{ locationInfo.address }}</div>
      <div class="location-coordinates">
        经度: {{ locationInfo.longitude.toFixed(6) }}, 纬度: {{ locationInfo.latitude.toFixed(6) }}
      </div>
    </div>
    <div class="map-controls">
      <el-input v-model="searchAddress" placeholder="搜索地址" class="search-input" @keyup.enter="handleSearch">
        <template #append>
          <el-button @click="handleSearch">
            <el-icon>
              <Search />
            </el-icon>
          </el-button>
        </template>
      </el-input>
      <el-button type="primary" @click="getCurrentLocation" class="location-btn">
        <el-icon>
          <Location />
        </el-icon> 当前定位
      </el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted, watch } from 'vue';
import AMapLoader from '@amap/amap-jsapi-loader';
import { Search, Location } from '@element-plus/icons-vue';
import { EpPropMergeType } from 'element-plus/es/utils';
import { ANY_OBJECT } from '@/types/generic';
// 注：若未使用表单注入，可删除form相关代码，避免报错
const form = inject('form', () => {
  console.warn('OnlineMapLocation: 未注入form上下文，默认使用非编辑模式');
  return { isEdit: false } as ANY_OBJECT;
});

// 声明全局AMap类型
declare global {
  interface Window {
    AMap: any;
  }
}

const props = withDefaults(
  defineProps<{
    widget: ANY_OBJECT | null;
    value?: string;
    align?: EpPropMergeType<
      StringConstructor,
      'center' | 'space-around' | 'space-between' | 'space-evenly' | 'end' | 'start',
      unknown
    >;
    width?: string;
    height?: string;
    zoom?: number;
    radius?: number;
    readOnly?: boolean;
    address: string;
  }>(),
  {
    align: 'start',
    width: '100%',
    height: '300px',
    zoom: 13,
    radius: 5,
    readOnly: false,
    address: ""
  },
);

const emit = defineEmits(['update:value', 'change']);

// 地图相关引用和状态
const mapContainer = ref<HTMLElement | null>(null);
const map = ref<any>(null);
const marker = ref<any>(null);
const searchAddress = ref('');
const locationInfo = ref({
  address: '',
  longitude: 116.397428, // 默认北京天安门（确保经纬度有效）
  latitude: 39.90923,
});
const isMapLoaded = ref(false);
const isEditMode = computed(() => form.isEdit && !props.readOnly);

// 容器样式（修复：确保radius单位正确）
const getContainerStyle = computed<ANY_OBJECT>(() => ({
  width: props.width,
  height: props.height,
}));

// 初始化地图（修复：移除重复的loadAMapScript，统一用AMapLoader）
const initMap = () => {
  if (!mapContainer.value || isMapLoaded.value) return;

  AMapLoader.load({
    key: 'ac51890ac2d4fca2b284ec586ef11720', // 替换为你的有效密钥（建议重新申请避免失效）
    version: '2.0',
    plugins: ['AMap.Geolocation', 'AMap.Geocoder', 'AMap.PlaceSearch'], // 新增PlaceSearch（搜索地址需用到）
    AMapUI: { version: '1.1', plugins: [] }, // 可选：加载AMapUI（若后续扩展功能）
  })
    .then((AMap) => {
      window.AMap = AMap; // 挂载到window，供后续方法使用
      createMap(); // 加载成功后创建地图
    })
    .catch((e) => {
      console.error('地图加载失败:', e);
      alert('地图初始化失败，请检查API密钥或网络'); // 增加用户提示，而非仅控制台打印
    });
};

// 创建地图实例（修复：标记拖拽事件、初始地址获取逻辑）
const createMap = () => {
  if (!window.AMap || !mapContainer.value) return;

  try {
    // 1. 创建地图实例
    map.value = new window.AMap.Map(mapContainer.value, {
      zoom: props.zoom,
      center: [locationInfo.value.longitude, locationInfo.value.latitude],
      resizeEnable: true,
      scrollWheel: isEditMode.value, // 编辑模式允许滚轮缩放，非编辑模式禁用
    });

    // 2. 创建标记
    marker.value = new window.AMap.Marker({
      position: [locationInfo.value.longitude, locationInfo.value.latitude],
      draggable: isEditMode.value,
      cursor: isEditMode.value ? 'move' : 'default',
      animation: 'AMAP_ANIMATION_DROP',
      icon: new window.AMap.Icon({ // 可选：自定义标记图标（增强视觉识别）
        size: new window.AMap.Size(30, 30),
        image: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_r.png',
        imageSize: new window.AMap.Size(30, 30),
      }),
    });
    map.value.add(marker.value);

    // 3. 初始经纬度获取地址（修复：确保经纬度有效再调用）
    if (locationInfo.value.longitude && locationInfo.value.latitude) {
      getAddressByLocation(locationInfo.value.longitude, locationInfo.value.latitude);
    }

    // 4. 编辑模式事件监听
    if (isEditMode.value) {
      // 地图点击事件：更新标记位置
      map.value.on('click', (e: any) => {
        const { lng, lat } = e.lnglat;
        marker.value.setPosition([lng, lat]);
        getAddressByLocation(lng, lat);
      });

      // 标记拖拽结束事件（修复：e.target.getPosition()获取经纬度）
      marker.value.on('dragend', () => {
        const position = marker.value.getPosition(); // 正确获取拖拽后的位置
        getAddressByLocation(position.lng, position.lat);
      });
    }

    isMapLoaded.value = true;
  } catch (error) {
    console.error('地图实例创建失败:', error);
  }
};

// 根据经纬度获取地址（核心修复：状态判断改为result.info === 'success'）
const getAddressByLocation = (lng: number, lat: number) => {
  if (!window.AMap) return;

  const geocoder = new window.AMap.Geocoder({
    radius: 1000,
    extensions: 'all', // 返回详细地址信息（如门牌号）
  });

  geocoder.getAddress([lng, lat], (status: string, result: any) => {
    // 修复：逆地理编码成功状态是'success'，而非'OK'

    if (status === 'complete' && result.info === 'OK') {
      const address = result.regeocode.formattedAddress;
      locationInfo.value = { address, longitude: lng, latitude: lat };
      updateFormValue(); // 更新表单值

    } else {
      console.error('地址获取失败:', result.info);
      locationInfo.value.address = '获取地址失败，请重试'; // 给用户明确提示
    }
  });
};

// 获取当前位置（优化：增加定位失败的用户提示）
const getCurrentLocation = () => {
  if (!window.AMap) return;

  const geolocation = new window.AMap.Geolocation({
    enableHighAccuracy: true, // 高精度定位（需要HTTPS环境）
    timeout: 20000,
    zoomToAccuracy: true, // 定位成功后自动缩放地图
    buttonPosition: 'RB', // 定位按钮放在右下角
    // 新增：IP定位失败后的降级配置
    noIpLocate: 0, // 0=允许IP定位，1=禁用IP定位（默认0，无需修改）
    useNative: true, // 优先使用浏览器原生定位（提高成功率）
  });

  geolocation.getCurrentPosition((status: string, result: any) => {
    if (status === 'complete') {
      const { lng, lat } = result.position;
      marker.value.setPosition([lng, lat]);
      map.value.setCenter([lng, lat]);
      getAddressByLocation(lng, lat);
    } else {
      console.error('定位失败:', result.message);
      alert(`定位失败：${result.message}，请检查位置权限`); // 增加用户提示
    }
  });

  map.value.addControl(geolocation); // 将定位按钮添加到地图
};

// 搜索地址（优化：搜索失败提示、清空无效输入）
const handleSearch = () => {
  if (!window.AMap || !searchAddress.value.trim()) return;

  const placeSearch = new window.AMap.PlaceSearch({
    city: '全国',
    pageSize: 1, // 只返回1个结果（避免多结果选择）
    pageIndex: 1,
  });

  placeSearch.search(searchAddress.value.trim(), (status: string, result: any) => {
    if (status === 'complete' && result.info === 'OK') {
      if (result.poiList.pois.length > 0) {
        const { location } = result.poiList.pois[0];
        marker.value.setPosition([location.lng, location.lat]);
        map.value.setCenter([location.lng, location.lat]);
        getAddressByLocation(location.lng, location.lat);
        searchAddress.value = ''; // 清空搜索框
      } else {
        alert('未找到匹配地址，请重新输入');
      }
    } else {
      console.error('地址搜索失败:', result.info);
      alert('搜索失败，请重试');
    }
  });
};

// 更新表单值（优化：避免重复JSON.stringify）
const updateFormValue = () => {
  const locationValue = JSON.stringify({
    address: locationInfo.value.address,
    longitude: locationInfo.value.longitude,
    latitude: locationInfo.value.latitude,
  });
  emit('update:value', locationValue);
  emit('change', locationValue);
};

// 解析位置数据（优化：增加异常捕获后的默认值）
const parseLocationData = (value: string | undefined) => {
  if (!value) return;

  try {
    const data = JSON.parse(value);
    if (data?.longitude && data?.latitude) {
      locationInfo.value = {
        address: data.address || '待获取地址',
        longitude: data.longitude,
        latitude: data.latitude,
      };
      // 地图已加载时更新标记位置
      if (map.value && marker.value) {
        marker.value.setPosition([data.longitude, data.latitude]);
        map.value.setCenter([data.longitude, data.latitude]);
      }
    }
  } catch (e) {
    console.warn('位置数据解析失败:', e);
    locationInfo.value = { address: '', longitude: 116.397428, latitude: 39.90923 }; // 重置默认值
  }
};

// 监听props.value变化（优化：immediate确保初始值生效）
watch(
  () => props.value,
  (newValue: any) => {
    parseLocationData(newValue);
    props.width = newValue.width
    props.height = newValue.height

  },
  {
    deep: true,
    immediate: true,
  },
);

// 监听编辑模式变化（优化：同步地图交互权限）
watch(
  () => isEditMode.value,
  (newValue) => {
    if (marker.value) {
      marker.value.setDraggable(newValue);
    }
    if (map.value) {
      map.value.setScrollWheel(newValue); // 编辑模式允许滚轮缩放
    }
  },
);

// 生命周期（优化：组件卸载时彻底销毁地图）
onMounted(() => {
  initMap();

});

onUnmounted(() => {
  if (map.value) {
    map.value.destroy(); // 销毁地图实例，释放资源
    map.value = null;
    marker.value = null;
    isMapLoaded.value = false;
  }
});
</script>

<style scoped>
.online-map-location {
  position: relative;
  width: 100%;
  margin-bottom: 16px;
}

.location-info {
  margin-top: 8px;
  font-size: 12px;
  color: #606266;
  line-height: 1.5;
}

.location-address {
  font-weight: 500;
  margin-bottom: 4px;
  color: #303133;
}

.map-controls {
  margin-top: 10px;
  display: flex;
  gap: 10px;
  align-items: center;
}

.search-input {
  flex: 1;
}

.location-btn {
  white-space: nowrap;
  padding: 0 16px;
}
</style>
